/*
 * @Descripttion: 
 * @version: 
 * @Author: SN
 * @Date: 2021-07-23 10:30:04
 * @LastEditors: SN
 * @LastEditTime: 2021-11-29 16:03:03
 */
import axios from 'axios'
import { requestSucess, requestRejected, responseSucess, responseRejected } from './axios-interceptors'
import Cookie from 'js-cookie'

const xsrfHeaderName = 'user-authorization'
const xsrfCookieName = 'Admin-Token'

axios.defaults.timeout = 5000
axios.defaults.withCredentials = true
axios.defaults.xsrfHeaderName = xsrfHeaderName
axios.defaults.xsrfCookieName = xsrfCookieName


// 认证类型
const AUTH_TYPE = {
  BEARER: 'Bearer',
  BASIC: 'basic',
  AUTH1: 'auth1',
  AUTH2: 'auth2',
}

/**
 * 加载 axios 请求拦截器
 * @param request
 */
axios.interceptors.request.use(
  config => requestSucess(config),
  error => requestRejected(error)
)

/**
 * 加载 axios 响应拦截器
 * response.data.respCode 提示和后端保持一致
 * @param response
 */
axios.interceptors.response.use(
  response => responseSucess(response),
  error => responseRejected(error)
)

// http method
const METHOD = {
  GET: 'get',
  POST: 'post'
}

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */

async function request (url, method, params, config) {
  switch (method) {
    case METHOD.GET:
      return axios.get(url, { params, ...config })
    case METHOD.POST:
      return axios.post(url, params, config)
    default:
      return axios.post(url, { params, ...config })
  }
}

/**
 * 设置认证信息
 * @param auth {Object}
 * @param authType {AUTH_TYPE} 认证类型，默认：{AUTH_TYPE.BEARER}
 */
 function setAuthorization (token, authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      Cookie.set(xsrfCookieName, token)
      break
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break
  }
}

export {
  METHOD,
  request,
  setAuthorization
}
